
import numpy as np
from player.base.player import Player
from openai import OpenAI

"""
Chat GPT
将你的gpt申请到的key替换api_key变量即可
"""
class GPTPlayer(Player):
    def __init__(self,api_key):
        super().__init__()
        self.api_key = api_key

    def step(self, board, pos, code, error_pos):
        # 将棋盘转换为字符串格式以便传递给 GPT
        board_str = "\n".join("".join(str(cell) for cell in row) for row in board)
        prompt = f"这是当前的棋盘状态：\n{board}\n你是黑棋（在棋盘上为1），请建议下一个最佳落子点，返回格式为：(row, col)。"

        client = OpenAI(
            # This is the default and can be omitted
            api_key=self.api_key
        )

        response = client.chat.completions.create(
            messages=[
                {"role": "user", "content": prompt}
            ],
            model="gpt-3.5-turbo",
        )
        # 从响应中提取坐标
        try:
            move_text = response['choices'][0]['message']['content'].strip()
            row, col = eval(move_text)  # 假设 GPT 的返回格式为 "(row, col)"
            return row, col
        except:
            # 如果解析失败，回退为随机下子
            return np.random.randint(0, 15), np.random.randint(0, 15)
